package filebus

import (
	"encoding/json"
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"gitee.com/dreamwood/ez-go/tools"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
)

const (
	FileBusEvent = "ez.FileBus"
)

type FileBus struct {
	Url  string
	Name string
	Uid  int64
	Data ss.M
}

func NewFileBus() *FileBus {
	return &FileBus{}
}
func (this *FileBus) Send() {
	content, _ := json.Marshal(this)
	err := ez.NsqProducer.Publish(FileBusEvent, content)
	if err != nil {
		println(err.Error())
	}
}

func CreateRandFile(suffix string) string {
	app := strings.ReplaceAll(ez.ConfigService.AppId, ".", "_")
	return fmt.Sprintf("./assets/%s/%s/%s%s", app, tools.GetDateYMD(), tools.CreateRandString(32), suffix)
}

func Subscribe(saveRoot string, cb func(bus *FileBus)) {
	ez.CreateNsqHandler(FileBusEvent, fmt.Sprintf("%s.%s", ez.ConfigService.AppId, ez.ConfigService.MachineCode), func(content []byte) error {
		fileBus := NewFileBus()
		_ = json.Unmarshal(content, &fileBus)
		//使用http.Get方法下载url的文件地址到本地saveRoot文件夹下
		// 发送HTTP GET请求
		resp, err := http.Get(fileBus.Url)
		if err != nil {
			println(err.Error())
			return err
		}
		defer resp.Body.Close()

		// 检查HTTP响应状态码
		if resp.StatusCode != http.StatusOK {
			println(fmt.Errorf("bad status: %s", resp.Status).Error())
			return fmt.Errorf("bad status: %s", resp.Status)
		}

		// 创建文件
		//从fileBus.Url中提取文件路径移除http://ip:port/
		urlObject, _ := url.ParseRequestURI(fileBus.Url)
		filepath := fmt.Sprintf("%s%s", saveRoot, urlObject.Path)

		tools.CreateDirForPath(filepath)
		out, err := os.Create(filepath)
		if err != nil {
			println(err.Error())
			return err
		}
		defer out.Close()

		// 将响应体写入文件
		_, err = io.Copy(out, resp.Body)
		cb(fileBus)
		ez.LogToConsoleNoTrace("FileBus:", filepath)
		return nil
	})
}
